//
//  QLYDNetWork.m
//  Pods-QLYDNetWork_Example
//
//  Created by fb on 2020/12/4.
//

#import "QLYDNetWork.h"
#import "QLYDHTTPSessionManager.h"
#import "QLYDNetWorkTools.h"
@implementation QLYDNetWork
/// update  http request headerFields
/// @param headers NSDictionary
+ (void)updateHeaderFields:(NSDictionary *)headers
{
    for(NSString *key in headers)
    {
        [[QLYDHTTPSessionManager shareSessionManager].requestSerializer setValue:[QLYDNetWorkTools stringFormat:headers[key]] forHTTPHeaderField:[QLYDNetWorkTools stringFormat:key]];
    }
    
}
/**
 获取http headers请求头
 */
+ (NSDictionary *)getHttpHeaderFields{
    return  [QLYDHTTPSessionManager shareSessionManager].requestSerializer.HTTPRequestHeaders;
}
/// A `POST` request.
/// @param urlString url
/// @param params Parameters
/// @param success A block object to be executed when the task finishes successfully.
/// @param fail A block object to be executed when the task finishes unsuccessfully.
+ (void)POST:(NSString*)urlString Parameters:(nullable id)params Success:(void (^)(id responseObject))success Fail:(void (^)(NSError *error))fail
{
    QLYDHTTPSessionManager *manager = [QLYDHTTPSessionManager shareSessionManager];
    
  if([params isKindOfClass:[NSString class]])
    {
        NSURL *URL = [NSURL URLWithString:urlString];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        NSMutableURLRequest *mutableRequest = [request mutableCopy];

        [manager.requestSerializer.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
            if (![request valueForHTTPHeaderField:field]) {
                [mutableRequest setValue:value forHTTPHeaderField:field];
            }
        }];

        [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        mutableRequest.HTTPMethod = @"POST";
        [mutableRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
     

        NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
          
            dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                fail(error);
            } else {
                NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
             
                    success(json);

              
            }
            });
        }];
        [dataTask resume];
       
        
    }else {
      
    [manager POST:urlString parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        ;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
      
        fail(error);

    }];
    }
  
    
}

///   A `GET` request.
/// @param urlString url
/// @param params Parameters
/// @param success  A block object to be executed when the task finishes successfully.
/// @param fail A block object to be executed when the task finishes unsuccessfully.
+ (void)GET:(NSString*)urlString Parameters:(id)params Success:(void (^)(id responseObject))success Fail:(void (^)(NSError *error))fail
{
    QLYDHTTPSessionManager *manager = [QLYDHTTPSessionManager shareSessionManager];
    [manager GET:urlString parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            ;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            fail(error);
        }];
     
}


/// 文件上传
/// @param urlStr 上传地址
/// @param data 数据流
/// @param fileName 文件名称
/// @param fileTye 文件类型
/// @param upProgress 进度
/// @param success  http state 200 返回 block
/// @param fail http 非 200 返回 http 错误信息
+ (void)postUploadWithUrl:(NSString *)urlStr fileData:(NSData *)data fileName:(NSString *)fileName fileType:(NSString *)fileTye  progress:(nullable void (^)(NSProgress *uploadProgress)) upProgress success:(void (^)(id responseObject))success fail:(void (^)(NSError *error))fail
{
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:data name:fileName ];
        } error:nil];
    QLYDHTTPSessionManager *manager = [QLYDHTTPSessionManager shareSessionManager];
    NSURLSessionUploadTask *uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
        upProgress(uploadProgress);
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          fail(error);
                      } else {
                          success(responseObject);
                      }
                  }];

    [uploadTask resume];
    
}

/// 下载文件
/// @param urlStr urlStr :   下载文件的url地址
/// @param fileUrl 存放路径
/// @param downProgress 进度条
/// @param success 结果和文件路径
/// @param fail <#fail description#>
+ (void)downloadWithUrl:(NSString *)urlStr documentsDirectoryURL:(NSURL *)fileUrl progress:(nullable void (^)(NSProgress *downProgress))downProgress success:(void (^)(id responseObject,NSURL *filePath))success fail:(void (^)(NSError *error))fail;
{
    QLYDHTTPSessionManager *manager = [QLYDHTTPSessionManager shareSessionManager];
    NSString *urlString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *uploadTask = [manager  downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        downProgress(downloadProgress);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [fileUrl URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        if(error)
        {
            fail(error);
        }else
        {
            success(response,filePath);
        }
    }];
    [uploadTask resume];
    
}
//info

@end
